#ifndef SIMUBOARD_SWITCHWIDGET_HPP
#define SIMUBOARD_SWITCHWIDGET_HPP

#include <FL/Fl_Box.H>
#include <string>

class Fl_PNG_Image;
class Fl_Image;

// 简单的开关控件：点击上半区 -> ON；点击下半区 -> OFF
class SwitchWidget : public Fl_Box
{
public:
    SwitchWidget(int x, int y, int w, int h, int pin_index);
    ~SwitchWidget() override;

    void set_pin(int pin) { pin_index_ = pin; }
    int pin() const { return pin_index_; }

    void set_state(bool on); // 仅更新UI
    bool state() const { return is_on_; }

    void sync_from_port(); // 从GPIO读取并更新UI

protected:
    void draw() override;
    int handle(int event) override;

private:
    void write_port(); // 将当前状态写入GPIO IN
    void ensure_images();
    void rebuild_cache_if_needed(int area_w, int area_h);

    bool is_on_ = false;
    int pin_index_ = 0;

    // 共享原始图片
    static Fl_PNG_Image* s_img_on_;
    static Fl_PNG_Image* s_img_off_;

    // 每实例缓存缩放后的图片
    Fl_Image* cached_img_ = nullptr;
    int cached_area_w_ = 0;
    int cached_area_h_ = 0;
    bool cached_on_ = false;
};

#endif // SIMUBOARD_SWITCHWIDGET_HPP

